package com.zpl.user.controller;

import com.zpl.core.Result;
import com.zpl.user.entity.Token;
import com.zpl.user.entity.User;
import com.zpl.user.service.UserService;
import com.zpl.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.Serializable;
import java.util.List;

import static com.zpl.user.Constrant.GlobalConstrant.TOKEN_PASSWORD;

/**
 * @author wangyuxin
 * @date 2020/9/21
 */
@RestController
@RequestMapping("/user")
@Api(value = "UserController", tags = {"系统用户管理"})
public class UserController {
//    测试网关路由,可删除

    @Autowired
    private UserService userService;

    @Autowired
    HttpServletRequest request;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedisTemplate<String, Serializable> redisCacheTemplate;

    @GetMapping
    public String getUser(){
        return "admin";
    }

    @GetMapping("/test")
    public Result test() {
        System.out.println("test");
        return Result.success("测试");
    }

    @PostMapping("/login")
    @ApiOperation(value = "1、获取账号名称", notes = "使用账号密码登录", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "账号名称", dataType = "String",required = true),
            @ApiImplicitParam(name = "password", value = "密码", dataType = "String")})
    public Result login(HttpServletRequest request ,String username, String password){
        if(userService.login(username, password)){
            HttpSession httpSession = request.getSession();
            User user = userService.getUserByUsername(username).get(0);
            Long id = user.getId();
            Long longObj = new Long(id);
            String Sid = longObj.toString();
            Token token=new Token();
            token.setToken(JwtUtils.sign(Sid,TOKEN_PASSWORD));
            httpSession.setAttribute("userId",id);
            return Result.success(token);

        }else {
            return Result.fail("登录失败");
        }
    }

    @PostMapping
    @ApiOperation(value = "2、添加用户", notes = "注册", httpMethod = "POST")
    @ApiImplicitParam(name = "user", value = "用户信息", dataType = "User",required = true)
    public Result insert(@RequestBody User user) {

//        redisCacheTemplate.opsForValue().set("user:", user);
//        User user1 = (User) redisCacheTemplate.opsForValue().get("user:");

        if (userService.insert(user)) {
            return Result.success("用户添加成功");
        }
        return Result.fail(user.getUsername() + "已存在！");
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "3、删除用户", notes = "通过id删除用户", httpMethod = "DELETE")
    @ApiImplicitParam(name = "id", value = "用户id", dataType = "Long")
    public Result delete(@PathVariable("id") Long id) {
        if (userService.delete(id)) {
            return Result.success("删除成功");
        }
        return Result.fail("删除失败");
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "4、获取用户", notes = "通过id获取用户", httpMethod = "GET")
    @ApiImplicitParam(name = "id", value = "用户id", dataType = "Long")
    public Result getUserById(@PathVariable("id") Long id) {
        User user = userService.getUserById(id);
        if (null != user) {
            return Result.success(user);
        }
        return Result.fail("id错误!");
    }

    @GetMapping("/list/{username}")
    @ApiOperation(value = "5、获取用户", notes = "通过用户名获取用户", httpMethod = "GET")
    @ApiImplicitParam(name = "username", value = "用户名", dataType = "String")
    public Result getUserByUsername(@PathVariable("username") String username) {
        List<User> list = userService.getUserByUsername(username);
        if (list.size()>0) {
            return Result.success(list);
        }
        return Result.fail("id错误!");
    }

    @PutMapping
    @ApiOperation(value = "6、更改用户", notes = "通过id更改用户", httpMethod = "PUT")
    @ApiImplicitParam(name = "user", value = "用户信息", dataType = "User",required = true)
    public Result update(@RequestBody User user) {
        if (userService.update(user)) {
            return Result.success("修改成功");
        }
        return Result.fail("修改失败");
    }

    @GetMapping("/alllist")
    @ApiOperation(value = "7、获取所有用户", notes = "获取所有用户", httpMethod = "GET")
    public Result getAllUser() {
        List<User> list = userService.getALLUser();
        return Result.success(list);
    }

    @GetMapping("/userid")
    @ApiOperation(value = "8、获取当前用户", notes = "通过session用户", httpMethod = "GET")
//    public Result getUserIdBySession(HttpSession httpSession){
//        if(httpSession.getAttribute("userId")==null){
//            return Result.fail("用户未登录");
//        }else{
//            Long userId = (Long) httpSession.getAttribute("userId");
//            return Result.success(userId);
//        }
//    }
    public Result getUserIdByToken(String username){
        if(userService.getUserByUsername(username)!=null){
            User user = userService.getUserByUsername(username).get(0);
            return Result.success(user);
        }
        return Result.fail("未找到该用户");
    }

    @GetMapping("/logout")
    @ApiOperation(value = "8、登出", notes = "登出", httpMethod = "GET")
    public Result logout(HttpSession httpSession){
        if(httpSession.getAttribute("userId")==null){
            return Result.fail("用户未登录");
        }else{
            httpSession.removeAttribute("userId");
            return Result.success("登出成功");
        }
    }





}
